package com.mytest.leetcode;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * Created by shixi  on 2019/6/24
 */
@Slf4j
public class Solution56 {

    public static void main(String[] args) {
        Solution56 solution = new Solution56();
        int [ ][ ] arr={{2,3},{4,5},{6,7},{8,9},{1,10}};;
        log.info("{}", solution.merge(arr));
    }
    public int[][] merge(int[][] intervals) {

        // 先排序

        Arrays.sort( intervals, new Comparator<int []>(){

            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        List<int[]>  mergerd = new ArrayList<>();
        for(int i=0;i< intervals.length;i++){
            if(i==0){
                mergerd.add(intervals[i]);
            } else {
                int left = mergerd.get(mergerd.size()-1)[1];
                int right = intervals[i][0];
                if(right > left ){
                    mergerd.add(intervals[i]);
                    continue;
                } else {
                    if (intervals[i][1] > left) {
                        mergerd.get(mergerd.size()-1)[1] = intervals[i][1];
                    }
                }
            }
        }
        return mergerd.toArray(new int[mergerd.size()][]);
    }
}

